<template>
  <el-form :model="detailForm" :rules="rules" ref="detailForm" :label-position="labelPosition"
           :class="isEdit?'':'formItem'">
    <el-card class="box-card" shadow="never">
      <div slot="header" class="header-card">
        <span class="header-card-title">装饰信息</span>
      </div>
      <el-row :gutter="24">
        <el-col :span="8" v-if="isShow">
          <el-form-item label="装饰预计开始日期:" prop="expectStartTime">
            <el-date-picker type="date" v-model="detailForm.expectStartTime" v-if="isEdit" value-format='yyyy-MM-dd'
                            style="width: 100%;" placeholder="选择装饰预计开始日期">
            </el-date-picker>
            <span v-else>{{ detailForm.expectStartTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="isShow">
          <el-form-item label="预计装饰结束日期:" prop="expectEndTime">
            <el-date-picker type="date" v-model="detailForm.expectEndTime" v-if="isEdit" value-format='yyyy-MM-dd'
                            style="width: 100%;" placeholder="选择预计装饰结束日期">
            </el-date-picker>
            <span v-else>{{ detailForm.expectEndTime }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8" v-if="isShow">
          <el-form-item label="供应商:" prop="supplierName">
            <el-select v-if="isEdit" v-model="detailForm.supplierId" @change="handleChange" style="width: 100%"
                       placeholder="输入供应商">
              <el-option v-for="item in options" :key="item.supplierId" :label="item.supplierName"
                         :value="item.supplierId">
              </el-option>
            </el-select>
            <span v-else>{{ detailForm.supplierName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="isShow">
          <el-form-item label="装饰费用:" prop="price">
            <el-input v-if="isEdit" v-model="detailForm.price"
                      v-thousand
                      disabled @change="changeAmount('price')" placeholder="输入装饰费用"/>
            <span v-else>{{ format_thousand(detailForm.price) }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24" v-if="isShow" style="margin-bottom: 16px;">

          <div class="decoration-illustrate">
            <span>精品装饰说明：</span>
          </div>
          <el-table size="mini" :data="detailForm.proList" border style="width: 100%"
                    :header-cell-class-name="headerClass">
            <el-table-column align="center" label="操作" v-if="isEdit" width="120">
              <template slot-scope="{row,$index}" v-if="row.decorateType == '2'">
                <el-button type="text" icon="el-icon-delete" @click="delDecoration(row, $index)">删除
                </el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" label="项目">
              <template #default="{row}">
                <el-input v-model="row.decorateName"
                          v-if="row.decorateType == '2' && isEdit"
                          placeholder="请输入项目名称" size="mini"></el-input>
                <span v-else>
                  {{ row.decorateName }}
                </span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="预算金额">
              <template #default="{row,$index}">
                <el-input v-model="row.budgetPrice" v-if="row.decorateType == '2' && isEdit"
                          size="mini" placeholder="请输入预算金额"
                          @change="changeTable(row, $index, 'budgetPrice')"></el-input>
                <span v-else>
                  {{ row.budgetPrice }}
                </span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="实际金额" prop="actualPrice">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'proList.'+$index+'.actualPrice'"
                              :rules="{required: state === 'write' && row.decorateType !== '2',  trigger: 'blur'}">
                  <el-input v-model="row.actualPrice" v-if="isEdit" size="mini"
                            placeholder="请输入实际金额"
                            @change="changeTable(row, $index, 'actualPrice')"/>
                  <span v-else>
                  {{ row.actualPrice }}
                </span>
                </el-form-item>
              </template>
            </el-table-column>
            <template v-slot:append v-if="isEdit">
              <div class="flex-xy-center" style="height: 30px">
                <e-button type="text" icon="eel-icon-plus" @click="addDecoration">添加
                </e-button>
              </div>
            </template>
          </el-table>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col v-if="isShow" :span="24">
          <el-form-item label="备注:">
            <el-input v-if="isEdit" placeholder="请输入备注" type="textarea" :rows="4"
                      v-model="detailForm.remark"></el-input>
            <span v-else style="margin:0;">{{ detailForm.remark }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>
  </el-form>
</template>

<script>
import {effectDate} from "@/utils/libs/effectDate.js"
import {getInsuranceSelectList} from "@/api/cwgd/insuranceSelect";

export default {

  name: 'decorationMessage',


  props: {
    value: {
      type: Object,
      default: () => {
        return {};
      },
    },
    state: {
      type: String,
      default: "",
    }

  },

  computed: {
    detailForm: {
      get() {
        let that = this
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key)
          },
          set(target, key, value) {
            that.$emit('input', {...target, [key]: value})
            return true
          }
        })
        return proxy
      }
    },
    labelPosition() {
      if (this.isEdit) {
        return "top";
      } else {
        return "left";
      }
    },
    isEdit() {
      let bool;
      switch (this.state) {
        case "write":
          bool = true;
          break;
        case "disabled":
          bool = false;
          break;
        case "readonly":
          bool = false;
          break;
      }
      return bool;
    },
  },


  watch: {},


  data() {
    var start = (rule, value, callback) => {
      let that = this
      if (value === '') {
        callback(new Error('装饰预计开始日期为空'));
      } else {
        if (new Date(value) > new Date(that.detailForm.expectEndTime)) {
          callback(new Error('装饰预计开始日期大于预计装饰结束日期'));
        } else {
          callback();
        }
      }
    };
    var end = (rule, value, callback) => {
      let that = this
      if (value === '') {
        callback(new Error('预计装饰结束日期为空'));
      } else {
        if (new Date(value) < new Date(that.detailForm.expectStartTime)) {
          callback(new Error('装饰预计开始日期小于装饰预计结束日期'));
        } else {
          callback();
        }
      }
    };
    return {
      isShow: true,
      rules: {
        expectStartTime: [{required: this.state === "write", validator: start, trigger: 'change'}],
        expectEndTime: [{required: this.state === "write", validator: end, trigger: 'change'}],
        supplierName: [{required: this.state === "write", message: '请输入供应商', trigger: 'blur'}],
        price: [{required: this.state === "write", message: '请输入装饰费用', trigger: 'blur'}],
      },
      options: [],
      headerList: ['actualPrice']
    };
  },

  created() {
    this.handleList()
  },
  mounted() {
  },
  methods: {
    headerClass({row, column, rowIndex, columnIndex}) {
      for (let i = 0; i < row.length; i++) {
        if (this.headerList.includes(row[i].property) && i == columnIndex && this.isEdit) {
          return "header-class";
        }
      }
    },

    handleList() {
      getInsuranceSelectList({businessTypeCode: ''}).then(res => {
        if (res.code === 200) {
          this.options = res.data
        }
      })
    },

    handleChange(val) {
      this.ids = val
      let index = this.options.findIndex(a => a.supplierId === val)
      if (index !== -1) {
        this.value.supplierId = this.detailForm.supplierId = val
        this.value.supplierName = this.detailForm.supplierName = this.options[index].supplierName
      }


    },

    //添加表格
    addDecoration() {
      let obj = {
        id: "",
        decorateId: "",
        decorateName: "",
        budgetPrice: "",
        actualPrice: "",
        remark: "",
        disabled: false,
        decorateType: "2",
      }
      this.detailForm.proList.push(obj)
    },
    //删除表格
    delDecoration(row, key) {
      this.detailForm.proList.splice(key, 1)
      this.handlePrice()
    },

    changeTable(row, key, field) {
      let _value
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/
      if (row[field]) {
        if (field == "actualPrice" || field == "budgetPrice") {
          if (msg.test(Number(row[field]))) {
            if (Number(row[field]) >= 0) {
              _value = row[field].toString().match(/^\d+(?:\.\d{0,2})?/)[0];
              row[field] = _value
            } else {
              row[field] = ""
            }
          } else {
            row[field] = ""
          }
          //  this.addAmountNun =  this.addAmount(this.detailForm.carMaintainProjectList , 'price')
          if (field === 'actualPrice') {
            this.handlePrice()
          }
        }
      }
    },

    handlePrice() {
      let num = 0
      for (let i = 0; i < this.value.proList.length; i++) {
        num += Number(this.value.proList[i].actualPrice)
      }
      this.value.price = num
    },

    //表单效验
    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.detailForm.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            this.locateToErr()
            reject()
          }
        });
      })
    },
    locateToErr() {

      this.$nextTick(() => {
        let isError = document.getElementsByClassName('is-error')
        isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: 'center',
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: 'smooth',
        })
      })
    },

    valid() {
      return new Promise((resolve) => {
        this.$refs.detailForm.validate((valid) => {
          resolve(valid);
        });
      })
    },

    changeAmount(str) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      if (!msg.test(this.detailForm[str])) {
        this.detailForm[str] = "";
      } else {
        let num = this.keepTwoDecimalPlaces(this.detailForm[str])
        this.detailForm[str] = num;
      }
    },

    keepTwoDecimalPlaces: function (num) {
      return num.toString().match(/^\d+(?:\.\d{0,2})?/)[0];
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/cwgd/formScss.scss";

.decoration-illustrate {
  display: flex;
  justify-content: space-between;
  font-size: 16px;
  margin-bottom: 10px;
  font-weight: 600;
}

::v-deep .header-class {
  .cell::before {
    content: "*";
    color: red;
    padding-right: 2px;
    font-size: 14px;
  }
}
</style>


